import { history } from 'umi';
import { stringify } from 'qs';
import { message } from 'antd';
import cookie from 'js-cookie';
import { fakeAccountLogin, getFakeCaptcha, logout, getImgCaptcha } from '@/services/api';

// import { setAuthority } from '@/utils/authority';
import { getPageQuery, clearLoginStates } from '@/utils/utils';
import { queryUserInfo } from '@/services/user';
import { eventTrack } from '@/utils/track';
import moment from 'moment';
import { transformCurUserInfo } from '@/utils';

export default {
    namespace: 'login',

    state: {
        status: undefined,
        organizeType: undefined,
        msg: '',
        users: {}
    },

    effects: {
        *login({ payload, callback }, { call, put, all }) {
            const response = yield call(fakeAccountLogin, payload);
            yield put({
                type: 'changeLoginStatus',
                payload: response?.data
            });
            // Login successfully
            if (response?.data?.code === 10000) {
                const { loginName = '' } = response?.data?.data;
                cookie.set('Authorization', response.response.headers.get('Authorization') || '', {
                    expires: 30
                });
                localStorage.setItem(
                    'loginInfo',
                    JSON.stringify({
                        ...response?.data?.data,
                        expTime: new Date().getTime() + response?.data?.data?.expiresIn * 1000
                    })
                );

                const [result] = yield all([call(queryUserInfo)]);
                if (result.code === 10000 || result.code === 20012 || result.code === 20013) {
                    // 注意：为了兼容组织架构接口改造与前端数据结构，故做一层数据转换
                    const finalUserInfo = transformCurUserInfo({ ...result.data, loginName });

                    localStorage.setItem('user', JSON.stringify(finalUserInfo));

                    yield put({
                        type: 'user/saveCurrentUser',
                        payload: finalUserInfo
                    });

                    const urlParams = new URL(window.location.href);
                    const params = getPageQuery();
                    let { redirect } = params;
                    if (redirect) {
                        const redirectUrlParams = new URL(redirect);
                        if (redirectUrlParams.origin === urlParams.origin) {
                            redirect = redirect.substr(urlParams.origin.length);
                            if (redirect.match(/^\/.*#/)) {
                                redirect = redirect.substr(redirect.indexOf('#') + 1);
                            }
                        } else {
                            redirect = null;
                        }
                    }

                    // 埋点
                    yield eventTrack({ eventName: 'login_click', loginStatus: 0 });
                    localStorage.setItem('eventTrackLogin', moment(new Date()).format('YYYY-MM-DD')); // 登录后今天上报一次防止重复上报
                    // sessionStorage.setItem('loginRedirect', redirect); // 登录后跳转地址！因为有菜单权限的校验，要在校验后在跳转，否则左侧菜单无法选中以及出现多个页签
                    yield put(history.replace('/'));
                } else {
                    message.error(result.msg);
                    // 埋点
                    eventTrack({ eventName: 'login_click', loginStatus: 1, errorInfo: result.msg });
                }
            } else {
                callback(response?.data);
                // 埋点
                eventTrack({ eventName: 'login_click', loginStatus: 1, errorInfo: response?.data?.msg });
                // message.error(response.data.msg);
            }
        },

        *getCaptcha({ payload }, { call }) {
            yield call(getFakeCaptcha, payload);
        },

        *logout(_, { put, call }) {
            const response = yield call(logout);
            if (response?.code === 10000) {
                yield put({
                    type: 'user/saveAvatarFile',
                    payload: ''
                });
                yield put({ type: 'userInfo/clear' });
                const { redirect } = getPageQuery();
                // redirect
                if (window.location.pathname !== '/user/login' && !redirect) {
                    yield put(
                        routerRedux.replace({
                            pathname: '/user/login',
                            search: stringify({
                                redirect: window.location.href
                            })
                        })
                    );
                }
                clearLoginStates();
            }
        },
        *getImgCaptcha({ payload, callback }, { call }) {
            const response = yield call(getImgCaptcha, payload);
            if (response.code === 10000) {
                callback(response.data);
            }
        }
    },

    reducers: {
        changeLoginStatus(state, { payload }) {
            return {
                ...state,
                ...payload,
                status: payload.code === 10000 ? 'ok' : 'error'
            };
        },
        save(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        }
    }
};
